package com.sogoodsoft.service.crm;

import java.util.List;
import java.util.StringTokenizer;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.sogoodsoft.dao.common.CommonHibernateDao;
import com.sogoodsoft.dao.crm.SmsDao;
import com.sogoodsoft.dao.crm.SmstaskDao;
import com.sogoodsoft.entity.account.User;
import com.sogoodsoft.entity.app.SysClass;
import com.sogoodsoft.entity.crm.Customer;
import com.sogoodsoft.entity.crm.Sms;
import com.sogoodsoft.entity.crm.Smstask;
import com.sogoodsoft.service.app.SysClassService;
import com.sogoodsoft.service.common.AbstractService;

@Component
@Transactional
public class SmstaskService extends AbstractService<Smstask, Long> {
	
	/**
	 * 任务同步状态
	 * false 状态下，定时任务暂停发短信
	 */
	private static boolean status = true;
	
	@Autowired
	private SmstaskDao dao;
	
	@Autowired
	private SmsDao smsDao;
	
	@Autowired
	private SysClassService sysService;
	
	@Autowired
	private AlertService alertService;
	
	@Override
	public CommonHibernateDao<Smstask, Long> getDao() {
		return dao;
	}
	
	/* 
	 * 按target生成数条短信，每个手机号一条
	 */
	public void save(Smstask task){
		status = false;
		try {
			//删除已生成的短信
			if(task.getId()!=null){
				List<Sms> smsList = task.getSmsList();
				for(Sms sms:smsList){
					smsDao.delete(sms);
				}
				task.setSmsList(null);
			}
			dao.save(task);
			
			//按target和模板生成短信
			StringTokenizer token = new StringTokenizer(task.getTarget(),",");
			
			//初始时，全部设为等待
			SysClass sendSatus = sysService.getByCode(Smstask.SEND_STATUS_CODE.WAIT.getCODE());
			task.setStatus(sendSatus);
			while(token.hasMoreElements()){
				String mobile = token.nextToken();
				Sms sms = new Sms();
				
				//按模板处理
				sms.setMsg(task.getMsg());
				sms.setPlantime(task.getPlantime());
				sms.setTarget(mobile);					
				sms.setTask(task);
				doTemplate(sms);
				sms.setSendSatus(sendSatus);
				smsDao.save(sms);
				
			}
			dao.save(task);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		status = true;
	}

	/* 
	 * 级联删除，同时删除关联的短信
	 */
	public void delete(Long id){
		Smstask task = dao.get(id);
		
		//删除已生成的短信
		if(task.getId()!=null){
			List<Sms> smsList = task.getSmsList();
			for(Sms sms:smsList){
				smsDao.delete(sms);
			}
		}
		
		//删除短信任务
		dao.delete(id);
	}
	
	/*
	 * 读取时，给target赋值，传递数据库里的手机号
	 */
	public Smstask get(Long id){
		Smstask task = null;
		task = dao.get(id);
		StringBuffer buffer = new StringBuffer();
		if(task!=null){
			List<Sms> smsList = task.getSmsList();
			for(Sms sms:smsList){
				buffer.append(",");
				buffer.append(sms.getTarget());
			}
			task.setTarget(buffer.substring(1));
		}		
		return task;
		
	}
	
	/**
	 * 根据手机号，取用户名，查询客户表和系统用户表
	 * <p>并且替换模板中定义的字段为对应字段</p>
	 * @param mobile
	 * @return
	 */
	@SuppressWarnings("rawtypes")
    public String doTemplate(Sms sms){
		String name = "";
		String target = sms.getTarget();
		String msg = sms.getMsg();
		User user = null;
		List list = null;
		String userHQL = "from User  where mobile=?";
		Customer customer = null;
		String customerHQL = "from Customer  where mobile=?";
		
		//查找系统用户手机号
		list = dao.find(userHQL, target);
		if(list.size()>0){
			user = (User)list.get(0);
			name = user.getName();
			sms.setName(name);	
			msg = msg.replace("${name}", name);
		}else{			
			//查找客户手机号
			list = dao.find(customerHQL, target);
			if(list.size()>0){
				customer = (Customer)list.get(0);	
				name = customer.getLinkman();
				sms.setName(name);
				msg = msg.replace("${name}", name);
				if(1==customer.getGender().longValue()){
					msg = msg.replace("${mrms}", "先生");
				}else{
					msg = msg.replace("${mrms}", "女士");
				}
			}
		}
		
		//对于没有查到的，替换为通用
		msg = msg.replace("${name}", "");
		msg = msg.replace("${mrms}", "（先生/女士）");
		sms.setMsg(msg);
		return name;
	}
	
	/**
	 * 结束任务时，修改任务状态
	 * @param task
	 */
	public void finishTask(Smstask task){
		 String taskHQL = "select count(*) from Sms where sendSatus.code=? and task.id=?";
		 Object count = null;
		//查询本任务是否还有待发短信
		 logger.debug("finish");
		count = getDao().findUnique(taskHQL, Smstask.SEND_STATUS_CODE.WAIT.getCODE(),task.getId());
		Long ct = (Long)count;
		if(ct.longValue()==0){
			//没有待发短信，本任务完成，更新任务状态
			SysClass status = sysService.getByCode(Smstask.SEND_STATUS_CODE.FINISH.getCODE());
			task.setStatus(status);
			dao.save(task);
			
			//结束其它相关模块
			finishOther(task);
		}
	}
	
	protected void finishOther(Smstask task){
		SysClass type = task.getType();
		//日程提醒完成
		if(Smstask.SEND_TYPE_CODE.ALERT.getCODE().equals(type.getCode())){
			alertService.AlertPublished(task.getSourceid());
		}
	}
	
	/**
	 * 已有短信发出的任务，不允许修改
	 * @param task
	 * @return
	 */
	public boolean editable(Smstask task){
		boolean editable = true;
		 String taskHQL = "select count(*) from Sms where sendSatus.code!=? and task.id=?";
		 Object count = null;
		 count = getDao().findUnique(taskHQL, Smstask.SEND_STATUS_CODE.WAIT.getCODE(),task.getId());
		 Long ct = (Long)count;
		 if(ct.longValue()>0){
			 editable = false;
		 }
		return editable;
	}
	
	public Smstask findBySounceId(Long sounceId){
		return dao.findUnique("from Smstask s where s.sourceid=?", sounceId);
	}

	public static boolean isStatus() {
		return status;
	}
	
	public SysClass getSmsType(String code){
		return sysService.getByCode(code);
	}

	
	
}
